<template>
  <div>
    <div class="login"><a @click="logout" class="login">注销</a></div>
    <div class="avatar">
      <el-avatar class="avatar" :size="100" :src="this.user.avatar"></el-avatar>
    </div>

    <div class="name"><h3>{{ this.user.username }}</h3></div>
    <div class="pres"><p>{{ this.user.description }}</p></div>
    <div class="editinfo"><a @click="editinfo">修改个人信息</a></div>

    <el-drawer
        title="讲文明树新风"
        :visible.sync="drawer"
        direction="btt"
        size="60%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
        </el-form-item>

        <!--头像上传组件-->
        <el-form-item>
          <el-upload
              class="upload-demo"
              action=""
              :before-upload="BeforeUpload"
              :http-request="Upload"
              list-type="picture">

            <el-tooltip class="item" effect="light" content="只能上传jpg/png文件，且不超过2mb" placement="bottom">
              <el-button type="primary" class="changeAvatar">更改头像</el-button>
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>


    </el-drawer>
    <hr>

    <div class="mylove">
      <van-cell is-link @click="showPopup"><h5>我的点赞</h5></van-cell>
      <van-popup v-model="show" class="myLike">
        <div v-for="blog in likeBlogs" class="myLikeItem">
          <h4>{{ blog.title }}</h4>
          <hr>
        </div>
      </van-popup>

      <van-cell is-link @click="showPopup2"><h5>我的收藏</h5></van-cell>
      <van-popup v-model="show2" class="myLike">
        <div v-for="blog in collectedBlogs" class="myLikeItem">
          <h4>{{ blog.title }}</h4>
          <hr>
        </div>
      </van-popup>
    </div>

    <!--    <div class="mylove">-->
    <!--      <el-button>我的收藏</el-button>-->
    <!--      <el-button>我的点赞</el-button>-->
    <!--    </div>-->
  </div>
</template>

<script>
import store from "../../store";

export default {
  inject: ["reload"],
  name: "user",

  data() {
    return {
      drawer: false,

      ruleForm: {
        username: '',
        email: '',
        description: '',
      },

      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {required: false, type: 'email', message: '请输入正确的邮箱', trigger: 'change'}
        ]
      },

      size: "large",
      // circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      user: '',
      show: false,
      show2: false,
      likeBlogs: [],
      collectedBlogs: [],

      //用于实现文件上传
      newFile: new FormData(),
    }
  },

  methods: {

    BeforeUpload(file) {

      const isImg = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false;
      }

      const isType = file.type === "image/png"
      const isType2 = file.type === "image/jpeg"

      if (!isType && !isType2) {
        this.$message.error('上传头像图片格式为png或jpg')
        return false
      }

      if (file) {
        this.newFile.append('file', file); //  2. 上传之前，拿到file对象，并将它添加到刚刚定义的FormData对象中。
        console.log(this.newFile.get('file'))
      } else {
        return false;
      }
    },

    Upload() {
      const newData = this.newFile;
      var _this = this
      this.$axios({
        url: '/user/avatarupload',
        method: 'post',
        data: newData,
        headers: {
          'Content-Type': 'multipart/ruleForm-data',
          "Authorization": localStorage.getItem("token")   //请求头携带的token
        }
      })
          .then(res => {
            console.log('res:', res)
            //后端更新后  前端还要刷新userinfo
            const userinfo = res.data.data //后端返回的登录用户信息（不包含密码）
            _this.$store.commit("SET_USERINFO", userinfo)

            _this.url = userinfo.avatar
            this.reload()
          })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('验证过')
          this.editUser()
        }
      })
    },
    editUser() {
      const _this = this

      if (this.ruleForm != null) {
        this.$axios.post('/user/editUser', this.ruleForm, {
          headers: {
            "Authorization": localStorage.getItem("token")
          }
        }).then(res => {
          this.$message({
            message: '修改成功',
            type: 'success'
          });

          const userinfo = res.data.data //后端返回的登录用户信息（不包含密码）

          this.username = userinfo.username
          this.email = userinfo.email
          _this.$store.commit("SET_USERINFO", userinfo)

          this.reload()

        })
      }
    },

    editinfo() {
      //回显用户信息
      var userinfo = this.$store.getters.getUser
      this.ruleForm.username = userinfo.username
      this.ruleForm.email = userinfo.email
      this.ruleForm.description = userinfo.description
      this.ruleForm.id = userinfo.id

      this.drawer = !this.drawer

    },

    showPopup() {
      this.show = true;
    },
    showPopup2() {
      this.show2 = true;
    },

    _isMobile() {
      let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
      return flag;
    },

    logout() {
      const _this = this
      _this.$axios.get("/logout", {
        headers: {"Authorization": localStorage.getItem("token")}
      }).then(res => {
        _this.$store.commit("REMOVE_INFO")


        if (this._isMobile()) {
          // alert("手机端");
          console.log('手机端')
          this.$router.replace('/mindex');
        } else {
          console.log('pc端')
          // this.$router.replace('/pc');
          this.$router.replace('/blogs');
        }

        // 这里有bug  我在blogs页面 logout 又push到/blog   Navigating to current location ("/blogs") is not allowed
        //解决办法： https://blog.csdn.net/weixin_43606809/article/details/103040805

        //发现图片不能刷新  手动
        this.reload()
      })
    },

    myCollectAndLike() {
      //返回收藏文章
      this.$axios.post("/showMyCollection", null, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.collectedBlogs = res.data.data
      })

      //返回点赞文章
      this.$axios.post("/showMyLike", null, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.likeBlogs = res.data.data
      })
    }

  },

  created() {
    this.user = store.getters.getUser;

    this.myCollectAndLike();

  }
}
</script>

<style scoped>

.demo-ruleForm {
  width: 90%;
  margin: auto;
  position: relative;
  right: 10px;
}

.upload-demo {
  display: inline-block;
}

a {
  color: #3d3d3d;
  font-size: small;
}

.editinfo {
  text-align: center;
}

.avatar {
  text-align: center;
  margin-top: 10px;
}

hr {
  margin-top: 20px;
}

.name {
  text-align: center;
}

.pres {
  text-align: center;
}

p {
  margin-top: 10px;
}

h3 {
  margin: 0;
}

h5 {
  font-size: medium;
  font-weight: 500;
  margin: 0;
}

.mylove {
  margin-top: 20px;
  text-align: center;
}

.myLike {
  height: 60%;
}

.login {
  text-align: right;
  margin-top: 2px;
  margin-right: 4px;
  color: #a8a8a8;
}

h4 {
  font-weight: 400;
}

.myLikeItem {
}
</style>
